import React, { useState } from 'react';
import { Empty, Skeleton, Button, Tooltip, Typography, Input, message } from 'antd';
import { CalendarOutlined, LogoutOutlined, BarChartOutlined } from '@ant-design/icons';
import { UserInfo, QuotaInfo } from '../../types/mainApp';
import { activateCode } from '../../services/mainApp';
import dayjs from 'dayjs';
import { AxiosError } from 'axios';
import { modal } from '../../utils/antd-static';
import './UserInfoCard.css';

const { Text, Title } = Typography;

interface UserInfoCardProps {
    userInfo: UserInfo | null;
    loading: boolean;
    onLogout: () => void;
    onActivationSuccess: (newQuotaInfo: QuotaInfo) => void;
}

const ActivationComponent: React.FC<{ 
    onActivationSuccess: (newQuotaInfo: QuotaInfo) => void;
    isCurrentlyActive: boolean;
}> = ({ onActivationSuccess, isCurrentlyActive }) => {
    const [code, setCode] = useState('');
    const [loading, setLoading] = useState(false);

    const activate = async () => {
        setLoading(true);
        try {
            const response = await activateCode(code);
            if (response.data.data) {
                message.success('激活成功！');
                onActivationSuccess(response.data.data);
                setCode('');
            }
        } catch (error) {
            const axiosError = error as AxiosError<{ message: string }>;
            message.error(axiosError.response?.data?.message || '激活失败，请稍后再试');
        } finally {
            setLoading(false);
        }
    };

    const handleActivate = async () => {
        if (!code.trim()) {
            message.warning('请输入卡密');
            return;
        }
        
        if (isCurrentlyActive) {
            modal.confirm({
                title: '确认操作',
                content: '当前套餐未过期，激活新卡密将会覆盖当前套餐，是否继续？',
                okText: '继续激活',
                cancelText: '取消',
                onOk: activate,
            });
        } else {
            await activate();
        }
    };

    const handleCodeQuery = async () => {
        message.warning('功能未开放');
    }

    return (
        <div className="activation-section">
            <Input 
                placeholder="请输入卡密"
                value={code}
                onChange={(e) => setCode(e.target.value)}
                style={{ flexGrow: 1 }}
            />
            <Button type="primary" onClick={handleActivate} loading={loading}>
                激活
            </Button>
            <Button type="default" onClick={handleCodeQuery} loading={loading}>
                查询
            </Button>
        </div>
    );
};

export const UserInfoCard: React.FC<UserInfoCardProps> = ({ userInfo, loading, onLogout, onActivationSuccess }) => {
    if (loading) {
        return (
            <div className="user-info-final">
                <Skeleton active paragraph={{ rows: 3, width: ['60%', '100%', '80%'] }} title={false} />
            </div>
        );
    }

    if (!userInfo) {
        return <Empty description="无法加载用户信息" />;
    }

    const { username, email, quotaInfo } = userInfo;

    return (
        <div className="user-info-final">
            <div className="user-header">
                <Title level={4} style={{ margin: 0, color: '#fff' }}>{username}</Title>
                <Tooltip title="登出" placement="right">
                    <Button 
                        type="text" 
                        shape="circle"
                        icon={<LogoutOutlined />} 
                        onClick={onLogout} 
                    />
                </Tooltip>
            </div>
            <Text type="secondary" style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '10px' }}>
                {email}
            </Text>

            {quotaInfo?.isCurrentlyActive && (
                <div className="quota-metrics">
                    <div className="metric-item">
                        <Text type="secondary" className="metric-label"><BarChartOutlined /> 额度</Text>
                        <div className="metric-value">
                            <span className="used-count">{quotaInfo.usedCount}</span>
                            <span className="total-count">/ {quotaInfo.totalCount}</span>
                        </div>
                    </div>
                     <div className="metric-item">
                        <Text type="secondary" className="metric-label"><CalendarOutlined /> 有效期</Text>
                        <div className="metric-value">
                            <span className="used-count">{dayjs(quotaInfo.expireTime).diff(dayjs(), 'day')}</span>
                            <span className="total-count">天</span>
                        </div>
                    </div>
                </div>
            )}
            
            <ActivationComponent 
                onActivationSuccess={onActivationSuccess}
                isCurrentlyActive={!!userInfo?.quotaInfo?.isCurrentlyActive}
            />
        </div>
    );
}; 